import { useCallback } from "react";
import { useProductsContext } from "./ProductsContextProvider";
import { getProducts } from "/src/services/products";
const useProducts = () => {
  const {
    isFetching,
    setIsFetching,
    products,
    setProducts,
    filters,
    setFilters,
  } = useProductsContext();
  const fetchProducts = useCallback(() => {
    setIsFetching(true);
    getProducts().then((products) => {
      setIsFetching(false);
      setProducts(products);
    });
  }, []);

  const filterProducts = (filters) => {
    setIsFetching(true);
    getProducts().then((products) => {
      setIsFetching(false);
      let filterdProducts;
      if (filters && filters.length > 0) {
        filterdProducts = products.filter((p) =>
          filters.find((filter) =>
            p.availableSizes.find((size) => size === filter)
          )
        );
      } else {
        filterProducts = products;
      }
      setFilters(filters);
      setProducts(filterdProducts);
    });
  };
  return {
    isFetching,
    products,
    filters,
    fetchProducts,
    filterProducts,
  };
};

export default useProducts;
